package com.codi.api.security;

import com.codi.bus.core.cache.UserInfoCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

@Slf4j
public abstract class UserUtil {

    private static final ThreadLocal<Long> LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<Long> PROFILE_ID = new ThreadLocal<>();


    /**
     * 机构id
     *
     * @return
     */
    public static Long getProfileId() {
        Long profileId = PROFILE_ID.get();
        return profileId;
    }

    public static void setProfileId(Long profileId) {
        PROFILE_ID.set(profileId);
        log.debug("===============>Uu：{}",profileId);

        if (profileId != null) {
            UserInfoCache.setIsOrg(true);
        } else {
            UserInfoCache.setIsOrg(false);
        }
    }


    public static String clearOrg() {
        StringBuffer str = new StringBuffer("clear ");
        Long profileId = PROFILE_ID.get();
        if (profileId != null) {
            log.info("clear profileId :{}", profileId);
            PROFILE_ID.remove();
            //UserInfoCache.remove();
            UserInfoCache.clear();
            str.append("profileId & userOrgInfo clear success!");
        } else {
            log.info("not clear profileId cause by profileId is null");
            str.append("profileId & userOrgInfo clear failed!");
        }
        return str.toString();
    }


    /**
     * update thread local as param, return old one
     */
    public static Long setUserId(Long userId) {
        Long now = LOCAL.get();
        LOCAL.set(userId);
        return now;
    }

    public static Long clear() {
        Long userId = LOCAL.get();
        if (userId != null) {
            log.debug("Clear user:" + userId);
        }
        LOCAL.remove();
        return userId;
    }

    /**
     * 获取当前登录的用户, 如果没有找到, 抛出异常
     */
    public static Long getLoginUserId() {
        Long userId = LOCAL.get();
        Assert.notNull(userId);
        return userId;
    }

    /**
     * 尽可能的尝试获取
     *
     * @return
     */
    public static Long getLoginUserIdIfNeed() {
        return LOCAL.get();
    }


}
